namespace SimpleWebServices.Web.UI.Html.Validation
{
    using System;
    using SimpleWebServices.Web.UI.Html.Elements;

    public sealed class RadioFieldsetValidator : Validator
    {
        public RadioFieldsetValidator()
            : this(null)
        {
        }

        public RadioFieldsetValidator(IInnerElements display)
            : base(display)
        {
            this.ErrorText = "You must select an item";
        }

        public override bool Validate(IElement element)
        {
            if (null == element)
            {
                throw new ArgumentNullException("element");
            }

            return this.Validate(element as Fieldset);
        }

        private static string GetValue(IInnerElements obj)
        {
            string result = null;

            if (null != obj)
            {
                foreach (IElement element in obj.Elements)
                {
                    result = GetValue(element as IInnerElements);
                    if (null != result)
                    {
                        break;
                    }

                    RadioInput input = element as RadioInput;
                    if (null != input && input.Checked)
                    {
                        result = input.Value;
                        break;
                    }
                }
            }

            return result;
        }

        private bool Validate(Fieldset fieldset)
        {
            if (null == fieldset)
            {
                throw new ArgumentOutOfRangeException("fieldset");
            }

            this.Errors.Clear();

            string value = GetValue(fieldset);
            if (null == value)
            {
                this.Errors.Add(new Error(this.ErrorText));
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}